import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import FTD from '..';
import styles from './index.module.less';

const Demo = (props) => {
  const { className } = props;

  const fixedRef = useRef(2);
  const runningRef = useRef(true);
  const [running, setRunning] = useState(true);
  const [dataSource, setDataSource] = useState(null);
  const [selectedDataKey, setSelectedDataKey] = useState(null);

  useEffect(() => {
    let interval = null;
    const timeout = setTimeout(() => {
      const ts = [5, 10, 15, 10, 5, 5, 10, 10, 20];
      const fs = [101.7, 102.7, 112.7, 92.7, 83.7, 121.7, 121.7, 100, 70];
      const bs = [10000, 20000, 15000, 25000, 30000, 10000, 10000, 10000, 15000];
      interval = setInterval(() => {
        if (runningRef?.current) {
          const rand = [];
          const len = ts.length - fixedRef.current;
          let n = Math.floor(Math.random() * len);
          while (rand.length < len) {
            while (rand.includes(n)) {
              n = Math.floor(Math.random() * len);
            }
            rand.push(n);
          }
          const d = [];
          for (let i = 0; i < rand.length; i += 1) {
            d.push({ frequency: fs[rand[i]], duration: ts[rand[i]], bandwidth: bs[rand[i]] });
          }
          setDataSource(
            d.map((dd, index) => {
              return { ...dd, serialNumber: index + 1 };
            }),
          );
        }
      }, 1000);

      const d = [];
      for (let i = 0; i < ts.length; i += 1) {
        d.push({ frequency: fs[i], duration: ts[i], bandwidth: bs[i] });
      }
      setDataSource(
        d.map((dd, index) => {
          return { ...dd, serialNumber: index + 1 };
        }),
      );
    }, 2000);
    return () => {
      clearInterval(interval);
      clearTimeout(timeout);
    };
  }, []);

  const onChange = () => {
    runningRef.current = !runningRef.current;
    setRunning(runningRef.current);
  };

  return (
    <>
      <FTD
        className={styles.ftd}
        centerFrequency={101.7}
        data={dataSource}
        selectedItemKey={selectedDataKey}
        onSelectionChange={(sn) => {
          setSelectedDataKey(sn);
        }}
      />
      <button className={styles.btn} type="button" onClick={onChange}>
        {running ? 'pause' : 'running'}
      </button>
    </>
  );
};

Demo.defaultProps = {
  className: null,
};

Demo.propTypes = {
  className: PropTypes.any,
};

export default Demo;
